/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hengtiansoft.lfy.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/***
 * 场景db sp
 */
public class CL_DbOpenHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 2;
    private static CL_DbOpenHelper instance;
    private static final String childCategroySQL="CREATE TABLE childCategroy (child_id INTEGER NOT NULL PRIMARY KEY,"
            +"categroy_id INTEGER NOT NULL,service_child_id INTEGER NOT NULL,"
            +"child_name TEXT NOT NULL, child_heat INTEGER NOT NULL DEFAULT 0,"
            +"isneedUpdate INTEGER NOT NULL DEFAULT 0,"
            +"datatime TEXT,"
            +"zip_name TEXT,"
            +"download_type INTEGER NOT NULL DEFAULT 0,"
            +"child_downloadsize TEXT DEFAULT 0, child_downloadcount TEXT DEFAULT 0, child_img_url TEXT);";
    private static final String childtypeSQL="CREATE TABLE childtype (child_id INTEGER NOT NULL, child_fen_id INTEGER NOT NULL,"
            +"isneedUpdate INTEGER NOT NULL DEFAULT 0,"
            +" child_fen_detail TEXT, child_fen_e_detail TEXT);";
    private static final String wordsSQL="CREATE TABLE words (words_id INTEGER NOT NULL PRIMARY KEY,"+
            "  child_id INTEGER NOT NULL,"+
            "  chinese TEXT NOT NULL,"+
            "  english TEXT NOT NULL,"+
            "  words_heat INTEGER NOT NULL DEFAULT 0,"+
            "  chinese_mp3path TEXT,"+
            "  english_mp3path TEXT,"+
            "  words_service_id TEXT,"+
            "  collect_server_id TEXT,"+
            "  words_iscollect TEXT DEFAULT 'N',"+
            "  childtype_id INTEGER NOT NULL);";
    //------------------------------------------------------------------
    private Context mContext=null;

    private CL_DbOpenHelper(Context context) {
        super(context, getUserDatabaseName(), null, DATABASE_VERSION);
        mContext=context;
    }

    public static CL_DbOpenHelper getInstance(Context context) {
        if (instance == null) {
            instance = new CL_DbOpenHelper(context.getApplicationContext());
        }
        return instance;
    }

    private static String getUserDatabaseName() {
        return "cl.db";//HXSDKHelper.getInstance().getHXId() +
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(childCategroySQL);
        db.execSQL(childtypeSQL);
        db.execSQL(wordsSQL);
        //--------------------------
        executeAssetsSQL(db,"cl.sql");
    }
    /**
     * 读取数据库文件（.sql），并执行sql语句
     * */
    private void executeAssetsSQL(SQLiteDatabase db, String schemaName) {
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(mContext.getAssets()
                    .open(schemaName)));

           // System.out.println("路径:"+Configuration.DB_PATH + "/" + schemaName);
            String line;
            String buffer = "";
            while ((line = in.readLine()) != null) {
                buffer += line;
                if (line.trim().endsWith(";")) {
                    db.execSQL(buffer.replace(";", ""));
                    buffer = "";
                }
            }
        } catch (IOException e) {
            Log.e("db-error", e.toString());
        } finally {
            try {
                if (in != null)
                    in.close();
            } catch (IOException e) {
                Log.e("db-error", e.toString());
            }
        }
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        switch (oldVersion) {
            case 1:
                db.execSQL("alter table words add column collect_server_id TEXT DEFAULT 0");
                db.execSQL("alter table words add column words_iscollect TEXT DEFAULT 'N'");
            break;

        }
    }

    public void closeDB() {
        if (instance != null) {
            try {
                SQLiteDatabase db = instance.getWritableDatabase();
                db.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            instance = null;
        }
    }

}
